package com.abcode.test.springbootmybatisplus.gen.common;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 分页实体对象转化为VO对象工具类
 *
 * @author qinzhitao
 * @date 2023/6/27 15:12
 */
public class PageUtil {

    /**
     * 分页实体对象转化为VO对象
     *
     * @param classObj   转化成的类型
     * @param sourcePage 要转化的分页对象
     * @return VO类分页对象
     */
    public static IPage convert(Class classObj, IPage sourcePage) {
        IPage targetPage = new Page();
        List<Object> sourceList = sourcePage.getRecords();
        //分页信息拷贝
        sourcePage.setRecords(new ArrayList());
        BeanUtils.copyProperties(sourcePage, targetPage);

        if (ObjectUtil.isNotEmpty(sourceList)) {
            //list信息拷贝
            List<Object> targetList = sourceList.stream().map(item -> {
                Object targetObj = null;
                try {
                    targetObj = classObj.newInstance();
                    BeanUtils.copyProperties(item, targetObj);
                } catch (InstantiationException e) {
                    throw new RuntimeException(e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
                return targetObj;
            }).collect(Collectors.toList());

            targetPage.setRecords(targetList);
        }
        return targetPage;
    }
}
